define(function (require) {
    var $ = require("jquery");
    require("pagination");
    require('angular-ui');
    require('global');
    var util = require("util");
    var ui = require("ui");
    var _ = require('underscore');
    var angular = require("angular");
    require('placeholder');
    require('angular-interceptor');
    require("angular-ui");
    require("/static_public/js/angular_directive/projectTreeSelector");//
    require('/static_public/node_modules/angular-file-upload/angular-file-upload');
    require('./salesmove');
    angular.module('salesTeamManage', [
        'ngInterceptor',
        'ngUI',
        'projectTreeSelector',//
        'ngPublicUI',
        'ngPlaceholder',
        'angularFileUpload',
        'salesMove'
    ])
        .constant('limit', 10)
        .constant('erplimit', 10)
        .constant('NEED_TOKEN', 'true')
        .constant('API', '/api/index.php?r=')
        .constant('PROJ','salesuser/sales-team/')
        .factory('url', [
            '$window',
            function ($window) {
                return {
                    //给url添加search字符串
                    addParam: function (url, search) {
                        for (var key in search) {
                            if (search.hasOwnProperty(key) && search[key]) {
                                var connecter = "&";
                                if (url.indexOf('?') === -1) {
                                    connecter = "?";
                                }
                                url += connecter + key + '=' + encodeURIComponent(search[key]);
                            }
                        }
                        return url;
                    },
                    getParam: function(param,url){
                        url = url || $window.location.href;
                        var match = url.match(new RegExp('[?&#]' + param + '=([^&#]+)'));
                        
                        return match && match[1];
                    }
                };
            }
        ])
        .factory('http', [
            '$http',
            'url',
            'API',
            'PROJ',
            'NEED_TOKEN',
            function ($http, url, API, PROJ, NEED_TOKEN) {
                return {
                    get: function (api, search,proj) {
                        var apiUrl = API + (proj || PROJ);
                        api = url.addParam(apiUrl + api, search);
                        return $http.get(api, { needToken: NEED_TOKEN });
                    },
                    post: function (api, data, search,proj) {
                        var dataMap = [];
                        for (var key in data) {
                            if (data.hasOwnProperty(key)) {
                                var val = data[key];
                                if (angular.isObject(val)) {
                                    val = JSON.stringify(val);
                                }
                                dataMap.push(key + '=' + encodeURIComponent(val));
                            }
                        }
                        data = dataMap.join('&');
                        var apiUrl = API + (proj || PROJ);
                        api = url.addParam(apiUrl + api, search);
                        return $http.post(api, data, {
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded'
                            },
                            needToken: NEED_TOKEN
                        });
                    }
                };
            }
        ])
        .factory('salesteamService', [
            'http',
            'url',
            'API',
            'PROJ',
            'FileUploader',
            function (http, url,API, PROJ,FileUploader) {
                var httpClient = {
                    get: function (api, options) {
                        return http.get(api, options.search,options.proj)
                            .success(function (res) {
                                if (res.retCode == 0) {
                                    return options.success(res);
                                }
                                options.fail && options.fail(res);
                            })
                            .error(function (res) {
                                options.fail && options.fail(res);
                            });
                    },
                    post: function (api, options) {
                        return http.post(api, options.data, options.search,options.proj)
                            .success(function (res) {
                                if (res.retCode == 0) {
                                    return options.success(res);
                                }
                                options.fail && options.fail(res);
                            })
                            .error(function (res) {
                                options.fail && options.fail(res);
                            });
                    }
                };

                return {
                    getProjectList: function (options) {
                        return httpClient.get('list', angular.extend(options,{
                            proj: "salesuser/project/"
                        }));
                    },
                    getMemberList: function(options){
                        return httpClient.get('select-user', options);
                    },
                    getTeamInfo: function (options) {
                        return httpClient.get('list', options);
                    },
                    createTeam: function(options) {
                        return httpClient.post('save-team', options);
                    },
                    updateTeam: function(options) {
                        return httpClient.post('save-team', options);
                    },
                    deleteTeam: function(options) {
                        return httpClient.get('delete-team', options);
                    },
                    importTeam: function(options) {
                        return httpClient.post('list', options);
                    },
                    exportMembers: function(options) {
                        return httpClient.post('list', options);
                    },
                    createSaleGroup: function(options) {
                        return httpClient.post('save-group', options);
                    },
                    updateSaleGroup: function(options) {
                        return httpClient.post('save-group', options);
                    },
                    deleteSaleGroup: function(options) {
                        return httpClient.get('delete-group', options);
                    },
                    createProjectManagers: function(options) {
                        return httpClient.post('add-project-managers', options);
                    },
                    deleteProjectManager: function(options) {
                        return httpClient.get('delete-project-manager', options);
                    },
                    createTeamManagers: function(options) {
                        return httpClient.post('add-team-managers', options);
                    },
                    deleteTeamManager: function(options) {
                        return httpClient.get('delete-team-manager', options);
                    },
                    createGroupLeaders: function(options) {
                        return httpClient.post('add-group-managers', options);
                    },
                    deleteGroupLeader: function(options) {
                        return httpClient.get('delete-group-manager', options);
                    },
                    createSalers: function(options) {
                        return httpClient.post('add-salers', options);
                    },
                    deleteSaler: function(options) {
                        return httpClient.post('delete-saler', options);
                    },
                    adjustGroup: function(options) {
                        return httpClient.post('move-saler', options);
                    },
                    updateSaler: function(options){
                        return httpClient.post('edit-saler', options);
                    },
                    importProTeam: function(options){
                        return httpClient.get('copy-team', options);
                    },
                    checkBindAssign: function(options){
                        return httpClient.get('check-bind-assign', options);
                    },
                    getTplDownLoadUrl: function (){
                        return API + PROJ + "download-template";
                    },
                    getMemberExportUrl: function(search){
                        return url.addParam(API + PROJ + "export",search);
                    },
                    getMemberImportUrl: function(search){
                        search = angular.extend(search||{},{
                            token: util.getQueryParams(location.search).token
                        });
                        return url.addParam(API + PROJ + "import",search);
                    },
                    getNotInTeamList: function(options){
                        return httpClient.get('get-init-sale-list', angular.extend(options,{
                            proj: "init/data-init/"
                        }));
                    },
                    createFileUploader: function (options) {
                        return new FileUploader({
                            url: this.getMemberImportUrl(options.search),
                            filters: options.filters || [],
                            autoUpload: false,
                            removeAfterUpload: false,
                            onCompleteItem: function (item, res) {
                                if (res.retCode == 0) {
                                    options.success && options.success(res);
                                    return;
                                }
                                options.fail && options.fail(res);
                            },
                            onAfterAddingFile : function(item){
                                options.appended && options.appended(item);
                            },
                            onErrorItem: function (item, res) {
                                options.fail && options.fail(res);
                            },
                            onWhenAddingFileFailed: function (item, filter) {
                                options.error && options.error(filter.name);
                            }
                        });
                    },
                    getHistoryList: function(options){
                        return httpClient.get('histroy-list', options);
                    },
                    comebackTeam: function(options){
                        return httpClient.get('move-in-team-user', options);
                    },
                    moveOutTeam: function(options){
                        return httpClient.get('move-out-team-user', options);
                    }
                };
            }
        ])
        .controller('SalesTeamController',[
            '$scope',
            '$rootScope',
            'url',
            'salesteamService',
            'erplimit',
            function ($scope,$rootScope,url,service,erplimit){
                /**
                 * 添加团队
                 */
                $scope.createTeam = function($data,$dialog){
                    if (!$data.team_name) {                     
                        $rootScope.$emit('httpRequestError',"请填写团队名称");
                        return false;
                    }
                    return service.createTeam({
                        data: {
                            proj_id:$scope.curProjectId,
                            team_name: $data.team_name
                        },
                        success: function(res){
                            $scope.update($scope.curProjectId);
                        },
                        fail: function(res){

                        }
                    });
                };
                /**
                 * 编辑团队
                 */
                $scope.updateTeam = function($data,$dialog,teamId){
                    return service.updateTeam({
                        data: {
                            proj_id:$scope.curProjectId,
                            team_name: $data.team_name,
                            team_id: teamId
                        },
                        success: function(res){
                            $scope.update($scope.curProjectId);
                        },
                        fail: function(res){}
                    });
                };
                /**
                 * 删除团队
                 */
                $scope.deleteTeam = function(teamId){
                    service.deleteTeam({
                        search: {
                            proj_id:$scope.curProjectId,
                            team_id: teamId
                        },
                        success: function(res){
                            $scope.update($scope.curProjectId);
                        },
                        fail: function(res){}
                    });
                };
                /**
                 * 添加销售组
                 */
                $scope.createSaleGroup =  function($data,$dialog){
                    if (!$data.group_name) {                     
                        $rootScope.$emit('httpRequestError',"请填写销售组名称");
                        return false;
                    }
                    return service.createSaleGroup({
                        data: {
                            proj_id:$scope.curProjectId,
                            group_name:$data.group_name,
                            team_id:$scope.currentTeam.team_id
                        },
                        success: function(res){
                            $scope.update($scope.curProjectId);
                        },
                        fail: function(res){}
                    });
                };
                /**
                 * 编辑销售组
                 */
                $scope.updateSaleGroup =  function($data,$dialog,groupId){
                    return service.updateSaleGroup({
                        data: {
                            proj_id:$scope.curProjectId,
                            group_id: groupId,
                            group_name:$data.group_name,
                            team_id:$scope.currentTeam.team_id
                        },
                        success: function(res){
                            $scope.update($scope.curProjectId);
                        },
                        fail: function(res){}
                    });
                };
                /**
                 * 删除销售组
                 */
                $scope.deleteSaleGroup =  function(groupId){
                    service.deleteSaleGroup({
                        search: {
                            group_id: groupId,
                            proj_id:$scope.curProjectId,
                            team_id:$scope.currentTeam.team_id
                        },
                        success: function(res){
                            $scope.update($scope.curProjectId);
                        },
                        fail: function(res){

                        }
                    });
                };
                /**
                 * 添加销售员
                 */
                $scope.addSalesMan =  function(){
                    service.addSalesMan({
                        data: {},
                        success: function(res){},
                        fail: function(res){}
                    });
                };
                /**
                 * 删除销售员
                 */
                $scope.deleteSalesMan =  function(){
                    service.deleteSalesMan({
                        data: {},
                        success: function(res){},
                        fail: function(res){}
                    });
                };
                /**
                 * 搜索成员列表
                 */
                $scope.searchMemberList = function(options){
                    var data = {
                        proj_id: $scope.curProjectId,
                        keyword: options.keyword,
                        page_index: options.pageIndex,
                        page_size: options.pageSize || erplimit
                    };
                    
                    if (options.team && options.team.team_id) {
                        angular.extend(data,{
                            team_id: options.team.team_id
                        })
                    }
                    service.getMemberList({
                        search: data,
                        success: function(res) {
                            options.success && options.success(res);
                        },
                        fail: function(res){

                        }
                    });
                };

                //添加成员控件
                $scope.initAddMemberDialog = function($dialogScope,team) {
                    $dialogScope.memberList = [];
                    $dialogScope.selectMemberList = [];
                    
                    $scope.searchMemberList({
                        pageIndex: 1,
                        keyword: '',
                        team:team,
                        success: function(res){
                            $dialogScope.memberList = res.data.data;
                            $dialogScope.pager.total = res.data.total;
                        }
                    });

                    $dialogScope.bindChecked = function(){
                        $dialogScope.checker.all = false;
                        var list = $dialogScope.memberList || [];
                        _.each(list,function(item){
                            if(_.findIndex($dialogScope.selectMemberList, {user_id:item.user_id}) !== -1){
                                item.checked = true;
                            }
                        });
                    };
                    //分页
                    $dialogScope.pager = {
                        pageSize: erplimit,
                        change: function(pageIndex){
                            $dialogScope.pager.pageIndex = pageIndex;
                            $scope.searchMemberList({
                                pageIndex: pageIndex,
                                keyword: $dialogScope.keyword,
                                team:team,
                                pageSize:$dialogScope.pager.pageSize,
                                success: function(res){
                                    $dialogScope.memberList = res.data.data;
                                    $dialogScope.pager.total = res.data.total;
                                    $dialogScope.bindChecked();
                                }
                            });
                        }
                    };

                    //搜索
                    $dialogScope.search = _.debounce(function () {
                        $scope.searchMemberList({
                            pageIndex: 1,
                            keyword: $dialogScope.keyword,
                            team:team,
                            pageSize:$dialogScope.pager.pageSize,
                            success: function(res){
                                $dialogScope.memberList = res.data.data;
                                $dialogScope.pager.total = res.data.total;
                            }
                        });
                    }, 250);

                    //checkbox
                    $dialogScope.checker = {
                        selectItem: function (index) {
                            var item = $dialogScope.memberList[index];
                            var checkedIndex = _.findIndex($dialogScope.selectMemberList, {user_id:item.user_id});
                            if (item.checked) {
                                checkedIndex === -1 && $dialogScope.selectMemberList.push(angular.copy(item));
                            }else if(!item.checked){

                                //如果全选按钮选中，则取消选中
                                $dialogScope.checker.all && ($dialogScope.checker.all = false);
                                checkedIndex !== -1 && $dialogScope.selectMemberList.splice(checkedIndex,1);
                            }
                        },
                        selectAll: function () {
                            var all = $dialogScope.checker.all;
                            if(all){
                                _.each($dialogScope.memberList,function(item,index){
                                    item.checked = true;
                                    $dialogScope.checker.selectItem(index);
                                });
                            }else{
                                _.each($dialogScope.memberList,function(item,index){
                                    item.checked = false;
                                    $dialogScope.checker.selectItem(index);
                                });
                            }
                        }
                    };
                    //移除
                    $dialogScope.removeItem = function(index,item){
                        var checkedItem = _.find($dialogScope.memberList, {user_id:item.user_id});
                        checkedItem  && (checkedItem.checked = false);
                        $dialogScope.selectMemberList.splice(index,1);
                    };

                };

                /**
                 * 添加项目经理
                 */
                $scope.createProjectManagers = function ($dialogScope){
                    var users = [];
                    for (var i = 0; i < $dialogScope.selectMemberList.length; i++) {
                        users.push($dialogScope.selectMemberList[i].user_id);
                    }
                    if (!users.length) {
                        $rootScope.$emit('httpRequestError',"请选择成员");
                        return false;
                    }
                    service.createProjectManagers({
                        data: {
                            proj_id: $scope.curProjectId,
                            users: users
                        },
                        success: function(res) {
                            $scope.update($scope.curProjectId);
                        },
                        fail: function(res){
                        }
                    });
                };
                /**
                 * 删除项目经理
                 */
                $scope.deleteProjectManager = function (userId){
                    service.deleteProjectManager({
                        search: {
                            proj_id: $scope.curProjectId,
                            team_user_id: userId
                        },
                        success: function(res) {
                            $scope.update($scope.curProjectId);
                        },
                        fail: function(res){
                        }
                    });
                };
                /**
                 * 添加团队经理
                 */
                $scope.createTeamManagers = function ($dialogScope,$dialog){
                    var users = [];
                    for (var i = 0; i < $dialogScope.selectMemberList.length; i++) {
                        users.push($dialogScope.selectMemberList[i].user_id);
                    }
                    if (!users.length) {
                        $rootScope.$emit('httpRequestError',"请选择成员");
                        return false;
                    }
                    return service.createTeamManagers({
                        data: {
                            proj_id: $scope.curProjectId,
                            team_id: $scope.currentTeam.team_id,
                            users: users
                        },
                        success: function(res) {
                            $scope.update($scope.curProjectId);
                        },
                        fail: function(res){
                        }
                    });
                };
                /**
                 * 删除团队经理
                 */
                $scope.deleteTeamManager = function (userId){
                    service.deleteTeamManager({
                        search: {
                            proj_id: $scope.curProjectId,
                            team_id: $scope.currentTeam.team_id,
                            team_user_id: userId
                        },
                        success: function(res) {
                            $scope.update($scope.curProjectId);
                        },
                        fail: function(res){
                        }
                    });
                };
                /**
                 * 添加销售组长
                 */
                $scope.createGroupLeaders =  function($dialogScope,$dialog,groupId){
                    var users = [];
                    for (var i = 0; i < $dialogScope.selectMemberList.length; i++) {
                        users.push($dialogScope.selectMemberList[i].user_id);
                    }
                    if (!users.length) {
                        $rootScope.$emit('httpRequestError',"请选择成员");
                        return false;
                    }
                    return service.createGroupLeaders({
                        data: {
                            proj_id: $scope.curProjectId,
                            team_id: $scope.currentTeam.team_id,
                            group_id: groupId,
                            users: users
                        },
                        success: function(res) {
                            $scope.update($scope.curProjectId);
                        },
                        fail: function(res){
                        }
                    });
                };
                /**
                 * 删除销售组长
                 */
                $scope.deleteGroupLeader =  function(userId,groupId){
                    service.deleteGroupLeader({
                        search: {
                            proj_id: $scope.curProjectId,
                            team_id: $scope.currentTeam.team_id,
                            group_id: groupId,
                            team_user_id: userId
                        },
                        success: function(res){
                            $scope.update($scope.curProjectId);
                        },
                        fail: function(res){}
                    });
                };
                /**
                 * 添加销售员
                 */
                $scope.createSalers =  function($dialogScope,$dialog,groupId){
                    var users = [];
                    for (var i = 0; i < $dialogScope.selectMemberList.length; i++) {
                        users.push($dialogScope.selectMemberList[i].user_id);
                    }
                    if (!users.length) {
                        $rootScope.$emit('httpRequestError',"请选择成员");
                        return false;
                    }
                    var data = {
                        proj_id: $scope.curProjectId,
                        users: users
                    };
                    if ($scope.currentTeam.team_id) {
                        angular.extend(data,{
                            team_id: $scope.currentTeam.team_id
                        })
                    }
                    if (groupId) {
                        angular.extend(data,{
                            group_id: groupId
                        })
                    }
                    return service.createSalers({
                        data: data,
                        success: function(res) {
                            $scope.update($scope.curProjectId);
                        },
                        fail: function(res){
                        }
                    });
                };
                /**
                 * 删除销售员
                 */
                $scope.deleteSaler =  function(userId,groupId){
                    var data = {
                        proj_id: $scope.curProjectId,
                        team_id: $scope.currentTeam.team_id,
                        team_user_id: userId
                    };

                    if (groupId) {
                        angular.extend(data,{
                            group_id: groupId
                        })
                    }
                    service.deleteSaler({
                        data: data,
                        success: function(res){
                            $scope.update($scope.curProjectId);
                        },
                        fail: function(res){}
                    });
                };
                /**
                 * 获取项目列表
                 */
                $scope.getProjectList = function(){
                    service.getProjectList({
                        search: {//
                            flag: "0",
                            jointparent: 1
                        },//
                        success: function (res) {
                            var data = res.data;
                            $scope.projectList = res.data || [];//
                            $scope.projectList.length === 0 && ($scope.notProject = true);
                        },
                        fail: function(res){

                        }
                    });
                };

                //上传控件
                $scope.getUploader = function ($dialogScope,$dialog) {
                    return service.createFileUploader({
                        search: {
                            proj_id: $scope.curProjectId
                        },
                        filters: [
                            {
                                name: 'excelFilter',
                                fn: function (item) {
                                    return /\.(xls|xlsx)$/.test(item.name);
                                }
                            }, {
                                name: 'sizeLimit',
                                fn: function (item) {
                                    return item.size < 2 * 1024 * 1024;
                                }
                            }
                        ],
                        success: function (res) {
                            $dialog.close();
                            $scope.update($scope.curProjectId);
                        },
                        error: function (filter) {
                            if (filter === "excelFilter") {
                                $rootScope.$emit('httpRequestError','请上传正确的Excel文件');
                            } else if (filter === "sizeLimit") {
                                $rootScope.$emit('httpRequestError','请选择2M以内的Excel文件');
                            }
                        },
                        fail: function (res) {
                            $rootScope.$emit('httpRequestError',res.errMsg);
                            $scope.update($scope.curProjectId);
                        }
                    });
                }

                //团队导入控件
                $scope.teamImporter = {
                    init : function($dialogScope,$dialog){
                        $dialogScope.uploader = null;
                        $dialogScope.uploader = $scope.getUploader($dialogScope,$dialog);
                        
                        $dialogScope.upload = function(){
                            if (!$dialogScope.uploader.queue.length) {
                                $rootScope.$emit('httpRequestError','请选择要导入的Excel文件');
                                return false;
                            }
                            $dialogScope.uploader.uploadItem($dialogScope.uploader.queue.length - 1);
                        }
                    }
                };
                
                $scope.tplDownLoadUrl = service.getTplDownLoadUrl();

                //调整组织
                $scope.adjustGroup = function ($dialog) {
                    var users = [];
                    var members = $rootScope.selectMemberList;
                    if (!members || !members.length) {
                        $rootScope.$emit('httpRequestError',"请选择成员");
                        return false;
                    }
                    
                    for (var i = 0; i < members.length; i++) {
                        users.push(members[i].user_id);
                    }
                    
                    var data = {
                        users: users,
                        proj_id: $scope.curProjectId
                    };
                    if (!$rootScope.selected) {
                        $rootScope.$emit('httpRequestError',"请选择新组织");
                        return false;
                    }
                    if ($rootScope.selected.group_id) {
                        angular.extend(data,{
                            target_group_id: $rootScope.selected.group_id
                        });
                    }
                    if ($rootScope.selected.team_id) {
                        angular.extend(data,{
                            target_team_id: $rootScope.selected.team_id
                        });
                    }

                    service.checkBindAssign({
                        search: {'saleIds': users, 'proj_id': $scope.curProjectId},
                        success: function (res) {
                            if (res.data) {
                                util.confirm(res.errMsg, {
                                    ok: function () {
                                        service.adjustGroup({
                                            data: data,
                                            success: function (res) {
                                                $scope.update($scope.curProjectId);
                                                $dialog.close();
                                            },
                                            fail: function (res) {
                                                //ui.showErrTip(res.errMsg);
                                            }
                                        });
                                    }
                                });
                            } else {
                                service.adjustGroup({
                                    data: data,
                                    success: function (res) {
                                        $scope.update($scope.curProjectId);
                                        $dialog.close();
                                    },
                                    fail: function (res) {
                                        //ui.showErrTip(res.errMsg);
                                    }
                                });
                            }
                        }
                    })                  
                    

                    return false;
                };

                //点击团队，选中团队
                $scope.setCurrentTeam = function(team,index){
                    $scope.currentTeam = team;
                    if (!$scope.currentTeam.groups || !$scope.currentTeam.groups.length) {
                        $scope.currentTeam.groups = [{
                            "group_managers": [],
                            "salers": []
                        }];
                    }
                    $scope.currentTeamIndex = index;
                };

                //组织调整控件
                $scope.groupAdjuster = {
                    init: function($dialogScope) {
                        $rootScope.selected = null;
                        $dialogScope.salesTeamInfo = $scope.salesTeamInfo;
                    }
                };

                //历史成员列表
                $scope.historys = {
                    historyMembersCount : 0,
                    getHistoryMembersCount: function(){
                        service.getHistoryList({
                            search: {
                                proj_id: $scope.curProjectId,
                                keyword: '',
                                page_index: 1,
                                page_size: 10
                            },
                            success: function(res){
                                $scope.historys.historyMembersCount = res.data.total;
                            },
                            fail: function(res){}
                        });
                    },
                    init: function($dialogScope){
                        //1 销售员 2 销售经理 3 团队经理 4 小组组长
                        $dialogScope.dictUser = {
                            '1': '销售员',
                            '2': '销售经理',
                            '3': '团队经理',
                            '4': '小组组长'
                        };
                        $dialogScope.query = {
                            keyword: '',
                            page_index: 1,
                            page_size: 10,
                            total: 0
                        };
                        $dialogScope.historyList = [];
                        $dialogScope.getList = function(index){
                            $dialogScope.query.page_index = index || 1;
                            service.getHistoryList({
                                search: {
                                    proj_id: $scope.curProjectId,
                                    keyword: $dialogScope.query.keyword,
                                    page_index: $dialogScope.query.page_index,
                                    page_size: $dialogScope.query.page_size
                                },
                                success: function(res){
                                    $dialogScope.historyList = res.data.items;
                                    $scope.historys.historyMembersCount = $dialogScope.query.total = res.data.total;
                                },
                                fail: function(res){}
                            });
                        };
                        $dialogScope.comebackTeam = function(team_user_id){
                            service.comebackTeam({
                                search: {
                                    team_user_id: team_user_id
                                },
                                success: function(res){
                                    $dialogScope.getList();
                                },
                                fail: function(res){}
                            });
                        };
                        $dialogScope.salesEditor = $scope.salesEditor;

                        $dialogScope_this = $dialogScope;
                        $dialogScope.updateSaler = function($dialogScope,$dialog){

                            $scope.updateSaler($dialogScope,$dialog,function(){
                                $dialogScope_this.getList();
                            });
                        };
                        //init
                        $dialogScope.getList();
                    }
                };
                $scope.moveOutTeam = function (team_user_id) {
                    util.confirm('<p style="text-align: center">确定将当前用户移出该团队吗？</p>' +
                        '<p>如果当前用户已离职，建议在成员管理中置为离职，会同时触发移出各团队；如果仅仅是调岗，请继续确定移出当前团队。</p>',
                        {
                            title: ' 移出团队',
                            width: '500',
                            ok: function () {
                                service.moveOutTeam({
                                    search: {
                                        team_user_id: team_user_id
                                    },
                                    success: function(res){
                                        if(res.data){
                                            util.notify('移出团队成功');
                                        }else{
                                            util.notify('移出团队成功！<br>该用户在当前项目下有客户数据，请处理客户数据！');
                                        }
                                        $scope.historys.historyMembersCount++;
                                        $scope.update($scope.curProjectId);
                                    },
                                    fail: function(res){}
                                });
                            }
                        });
                };

                $scope.notInTeamViewer = {
                    init: function(scope) {
                        scope.dictUser = {
                            '1': '销售员',
                            '2': '销售经理',
                            '3': '团队经理',
                            '4': '小组组长'
                        };
                        scope.getNotInTeamList = function(opts){
                            opts = opts || {
                                page_index: 1,
                                page_size: 10
                            };
                            
                            service.getNotInTeamList({
                                search: angular.extend(opts,{
                                    keyword : scope.keyword || "",
                                    proj_id: $scope.curProjectId
                                }),
                                success: function(res){
                                    scope.notInTeamList = res.data.items;
                                    scope.pager.total = res.data.total;
                                    scope.pager.pageIndex = opts.page_index;
                                    scope.keyword = "";
                                }
                            });
                        };
                        
                        scope.search = function(){
                            scope.keyword = scope.search_text;
                            scope.getNotInTeamList();
                        };
                        
                        /** 
                         * 分页组件
                         */
                        scope.pager = {
                            pageIndex: 1,
                            pageSize: 10,
                            change: function(pageIndex){
                                scope.getNotInTeamList({
                                    page_index: pageIndex,
                                    page_size: scope.pager.pageSize
                                });
                            }
                        };
                        
                        scope.getNotInTeamList();
                    },
                    fetch: function(){
                        service.getNotInTeamList({
                            search: {
                                page_index: 1,
                                page_size: 10,
                                proj_id: $scope.curProjectId
                            },
                            success: function(res){
                                $scope.notInTeamViewer.memberCount = res.data.total;
                            }
                        });
                    }
                };
                $scope.salesEditor = {
                    init: function ($dialogScope, user) {
                        $dialogScope.user = user;
                        $dialogScope.user_type = user.user_type;
                        $dialogScope.roles = ['置业顾问','销售经理', '团队经理','销售组长'];
                        if ($scope.noTeam) {                        
                            $dialogScope.roles = ['置业顾问','销售经理'];
                        }
                        
                        $dialogScope.noTeam = $scope.noTeam;
                        $dialogScope.salesTeamInfo = $scope.salesTeamInfo;
                        $dialogScope.toggleTree = function(){
                            $scope.salesEditor.toggleTree($dialogScope);
                        }
                        $dialogScope.change = function(type){
                            $dialogScope.user_type = type;
                            $dialogScope.selected = null;
                        };
                        $scope.salesEditor.showTree($dialogScope,$dialogScope.salesTeamInfo,$scope.currentTeam);
                    },
                    toggleTree: function(scope){
                        scope.showTree = !scope.showTree;
                        scope.treeDisplay = {
                            border:"none",
                            display: scope.showTree ? "block": "none"
                        };
                    },
                    showTree: function (scope,teamInfo,currentTeam) {
                        //scope.showTree = true;
                        var teams = teamInfo.teams;
                        var teamList = [];
                        for (var i = 0; i < teams.length; i++) {
                            var team = teams[i];
                            if (!team.team_id) {
                                break;
                            }
                            teamList[i] = {};
                            teamList[i].name = team.team_name;
                            teamList[i].data = [i];

                            if (team.groups && team.groups.length && team.groups[0].group_name) {
                                teamList[i].children = [];
                                for (var j = 0; j < team.groups.length; j++) {
                                    teamList[i].children.push({
                                        name: team.groups[j].group_name,
                                        data: [i, j]
                                    });
                                }
                            }

                        }
                        if (!teamList.length) {
                            scope.showTree = false;
                            return;
                        }
                        //左侧组织名称
                        var $tree = $('#tree_table');
                        $tree.tree("destroy");
                        $tree.tree({
                            data: teamList,
                            dragAndDrop: false,
                            useContextMenu: false,
                            autoOpen: 0, //展开级别
                            onCreateLi: function (node, $li) {
                            },
                            //是否可以移动
                            onCanMove: function (node) {
                                return false;
                            },
                            //是否可以移动到
                            onCanMoveTo: function (moved_node, target_node, position) {
                                //只能在同级节点中移动
                                return false;
                            },
                            //移动句柄
                            onIsMoveHandle: function ($ele) {
                                return false;
                            }
                        })
                            .on('tree.click', function (event) {
                                if (event.node) {
                                    var data = event.node.data;
                                    if (data.length === 1) {

                                        if (scope.user_type == "置业顾问"){
                                            var team = teams[data[0]];
                                            if (!(team.groups && team.groups[0] && team.groups[0].group_id)) {
                                                scope.selected = teams[data[0]];
                                            }
                                        } else if (scope.user_type === "销售组长") {
                                            
                                        } else {
                                            scope.selected = teams[data[0]];
                                        }
                                        
                                    } else {
                                        if (scope.user_type === "置业顾问" || scope.user_type === "销售组长") {
                                            scope.selected = teams[data[0]].groups[data[1]];
                                        }                                       
                                    }
                                    scope.toggleTree();
                                    scope.$apply();
                                }
                            });

                        //scope.selected = currentTeam;
                    }
                };

                $scope.updateSaler = function($dialogScope,$dialog,callback){
                    var user_type = $dialogScope.user_type || $dialogScope.user.user_type;
                    var types = ['置业顾问', '销售经理', '团队经理', '销售组长'];
                    for (var i = 0; i < types.length; i++) {
                        if (types[i] === user_type) {
                            break;
                        }
                    }

                    if (user_type === "销售经理") {
                        $dialogScope.selected = null;
                    } else {
                        if (!$dialogScope.selected && !$scope.noTeam) {
                            $rootScope.$emit('httpRequestError',"请选择团队或小组");
                            return false;
                        }
                    }
                    
                    var data = {
                        team_user_id: $dialogScope.user.team_user_id,
                        user_type: i + 1
                    };

                    if ($dialogScope.selected && $dialogScope.selected.group_id) {
                        angular.extend(data,{
                            target_group_id: $dialogScope.selected.group_id
                        });
                    }
                    if ($dialogScope.selected && $dialogScope.selected.team_id) {
                        angular.extend(data,{
                            target_team_id: $dialogScope.selected.team_id
                        });
                    }

                    // 回归团队时,callback is funciton
                    if(!angular.isFunction(callback)){
                        service.checkBindAssign({
                            search:{'saleIds':$dialogScope.user.user_id,'proj_id':$scope.curProjectId},
                            success:function(res){
                                if(res.data){
                                    util.confirm(res.errMsg, {
                                        ok: function () {
                                            service.updateSaler({
                                                data: data,
                                                success: function(res) {
                                                    $dialog.close();
                                                    $scope.update($scope.curProjectId);
                                                    angular.isFunction(callback) && callback();
                                                },
                                                fail: function(res){

                                                }
                                            });
                                        }
                                    });
                                }else{
                                    service.updateSaler({
                                        data: data,
                                        success: function(res) {
                                            $dialog.close();
                                            $scope.update($scope.curProjectId);
                                            angular.isFunction(callback) && callback();
                                        },
                                        fail: function(res){

                                        }
                                    });
                                }
                            }
                        });
                    }else{
                        service.updateSaler({
                            data: data,
                            success: function(res) {
                                $dialog.close();
                                $scope.update($scope.curProjectId);
                                angular.isFunction(callback) && callback();
                            },
                            fail: function(res){

                            }
                        });
                    }

                    
                    return false;
                };

                $scope.proTeamImporter = {
                    init: function($dialogScope) {
                        $dialogScope.projectList = $scope.projectList;
                    }
                };
                
                $scope.importProTeam = function($dialogScope,$dialog) {
                    if ($scope.curProjectId === $dialogScope.curProjectId) {                       
                        $rootScope.$emit('httpRequestError',"不能选择当前项目");
                        return false;
                    }
                    return service.importProTeam({
                        search: {
                            target_proj_id: $scope.curProjectId,
                            proj_id: $dialogScope.curProjectId
                        },
                        success: function(res) {
                            $scope.update($scope.curProjectId);
                        },
                        fail: function(res){

                        }
                    });
                };
                
                $scope.update = function(projectId){
                    service.getTeamInfo({
                        search: {
                            proj_id:projectId
                        },
                        success: function(res){
                            var info = res.data;
                            if (!info.project_managers) {
                                info.project_managers = [];
                            }
                            if (!info.teams || info.teams.length === 0) {
                                info.teams = [{
                                    "team_managers": [],
                                    "groups": [
                                        {
                                            "group_managers": [],
                                            "salers": []
                                        }
                                    ]
                                }]
                            }

                            for (var j = 0; j < info.teams.length; j++) {
                                var team = info.teams[j];
                                if (!team.team_managers) {
                                    team.team_managers = [];
                                }
                                if (!team.groups) {
                                    team.groups = [
                                        {
                                            "group_managers": [],
                                            "salers": []
                                        }
                                    ];

                                    for (var k = 0; k < team.groups.length; k++) {
                                        var group = team.groups[k];
                                        if (!group.group_managers) {
                                            group.group_managers = [];
                                        }
                                        if (!group.salers) {
                                            group.salers = [];
                                        }
                                    }
                                }
                            }
                            $scope.salesTeamInfo = info;
                            $rootScope.salesTeamInfo = info;
                            var selectedTeam = $scope.salesTeamInfo.teams[$scope.currentTeamIndex || 0];
                            if (selectedTeam && selectedTeam.team_id &&  $scope.currentTeam && $scope.currentTeam.team_id) {
                                $scope.setCurrentTeam(selectedTeam,$scope.currentTeamIndex || 0);
                                return;
                            }
                                                                           
                            $scope.setCurrentTeam($scope.salesTeamInfo.teams[0],0);
                            
                        },
                        fail: function(res){

                        }
                    });

                };

                //监听项目变化
                $scope.$watch('curProjectId', function () {
                    if ($scope.curProjectId) {
                        $scope.update($scope.curProjectId);

                        $scope.memberExportUrl = service.getMemberExportUrl({
                            proj_id: $scope.curProjectId
                        });

                        // 获取历史成员
                        $scope.historys.getHistoryMembersCount();
                        //获取不在销售团队的销售员
                        $scope.notInTeamViewer.fetch();
                        
                    }
                });

                $scope.$watch('salesTeamInfo',function(info){
                    var noMember = true;
                    var noTeam = true;
                    if (info) {
                        if (info.project_managers && info.project_managers.length && info.project_managers[0].user_id) {
                            noMember = false;
                        } else if (!info.teams || info.teams.length === 1){
                            if (info.teams) {
                                var team = info.teams[0];
                                if (team.groups) {
                                    var group = team.groups[0];
                                    if (group.group_managers && group.group_managers.length && group.group_managers[0].user_id) {
                                        noMember = false;
                                    } else if (group.salers && group.salers.length && group.salers[0].user_id) {
                                        noMember = false;
                                    }                              
                                }
                            }
                        } else {
                            noMember = false;
                            noTeam = false;
                        }
                        
                        if (info.teams && info.teams.length && info.teams[0].team_id) {
                            noTeam = false;
                        }
                        
                        $scope.noMember = noMember;
                    }                         
                    $scope.noTeam = noTeam;            
                });

                // init
                $scope.getProjectList();
                
                
                var proj_id = url.getParam('projId');
                
                if (proj_id) {
                    $scope.curProjectId = proj_id;
                }
            }
        ])

    angular.element(document).ready(function () {
        angular.bootstrap(document, ["salesTeamManage"]);
    });
});
